# ~*~ coding: utf-8 ~*~

from .connection import SSHConnection
from .models import Server
from .session import Session

BUF_SIZE = 4096


class ProxyServer(object):

    def __init__(self, client, asset, system_user):
        self.client = client
        self.asset = asset
        self.system_user = system_user
        self.server = None
        self.session = None

    @staticmethod
    def validate_permission(user, asset, system_user):
        """
        验证用户是否有连接该资产的权限
        :return:
        """
        if not user.has_asset_connect_perm(asset, system_user):
            raise PermissionError("Permission deny")

    def get_ssh_server_conn(self):
        """
        通过客户端请求的asset和system_user获取服务器的chan
        :return:
        """
        request = self.client.request
        self.validate_permission(self.client.user, self.asset, self.system_user)

        term = request.meta.get('term', 'xterm')
        width = request.meta.get('width', 80)
        height = request.meta.get('height', 24)
        conn = SSHConnection.new_connection(
            self.client.user, self.asset, self.system_user
        )
        chan = conn.get_channel(term=term, width=width, height=height)
        server = Server(chan, conn, self.asset, self.system_user)
        return server

    def proxy(self):
        self.server = self.get_ssh_server_conn()

        self.session = Session.new_session(self.client, self.server)
        # 5分钟没有输入session自动关闭连接
        self.session.set_timeout(60 * 1)
        try:
            self.session.bridge()
        finally:
            self.session.remove_session(self.session.sid)

    def stop(self):
        if self.session:
            self.session.close()
